﻿<div id="app" class="common-layout" style="max-width: max-content;">
    <div id="tableBlock">
        <!-- 查询区域 -->
        <div class="search-area">
            <div class="search-row">
                <div class="search-item">
                    <label>出库单号：</label>
                    <el-input type="text" v-model="searchForm.stockOutOrderNo" class="formTableInput" placeholder="请输入出库单号"></el-input>
                </div>
                <div class="search-item">
                    <label>出库类型：</label>
                    <el-select v-model="searchForm.stockOutType" class="formTableSelect" placeholder="请选择出库类型">
                        <el-option label="全部" value=""></el-option>
                        <el-option v-for="item in outboundTypes"
                                   :key="item.label"
                                   :label="item.value"
                                   :value="item.label">
                        </el-option>
                    </el-select>
                </div>
                <div class="search-item">
                    <label>状态：</label>
                    <el-select v-model="searchForm.status" class="formTableSelect" placeholder="请选择状态">
                        <el-option label="全部" value=""></el-option>
                        <el-option v-for="item in statusList"
                                   :key="item.label"
                                   :label="item.value"
                                   :value="item.label">
                        </el-option>
                    </el-select>
                </div>
                <!-- 仓库选择下拉框 -->
                <div class="search-item">
                    <label>仓库：</label>
                    <el-cascader v-model="searchForm.warehouseLocation"
                                 class="formTableSelect"
                                 placeholder="请选择仓库/库位"
                                 :options="warehouseLocationOptions"
                                 :props="{ expandTrigger: 'hover', label: 'name', value: 'id', children: 'children' }"
                                 clearable>
                    </el-cascader>
                </div>
                <div class="search-row">
                    <el-button type="default" v-on:click="resetForm">重置</el-button>
                    <el-button type="primary" v-on:click="searchTable">查询</el-button>
                </div>
            </div>

            <!-- 操作按钮区域 -->
            <div class="buttonBlock">
                <el-button type="primary" v-on:click="addOutboundOrder">新增</el-button>
                <el-button type="default" v-on:click="editOutboundOrder">编辑</el-button>
                <el-button type="success"
                           v-on:click="batchAuditOutboundOrder"
                           :disabled="selectedRows.length === 0">
                    审核
                </el-button>
                <el-button type="default" v-on:click="deleteOutboundOrder">删除</el-button>
                <el-button type="default" v-on:click="copyOutboundOrder">复制</el-button>
                <el-button type="default" v-on:click="exportTable">导出</el-button>
                <el-button type="default" v-on:click="importOutboundOrder">导入</el-button>
                <el-button type="success" v-on:click="refreshTable">刷新</el-button>
            </div>
        </div>

        <!-- 表格区域 -->
        <div class="btnAndTable">
            <el-table :data="paginatedData"
                      style="width: 100%; margin-top: 10px"
                      v-on:selection-change="handleSelectionChange"
                      ref="multipleTable"
                      stripe
                      border>
                <el-table-column fixed type="selection" width="50"></el-table-column>
                <el-table-column fixed label="出库单号" width="150">
                    <template #default="scope">
                        <span style="color: #10b981; cursor: pointer;" v-on:click="jumpToDetail(scope.row)">
                            <span v-html="highlightText(scope.row.stockOutOrderNo, searchForm.stockOutOrderNo)"></span>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column fixed label="出库类型" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(getOutboundTypeText(scope.row.stockOutType), searchForm.stockOutType)"></span>
                    </template>
                </el-table-column>
                <el-table-column fixed prop="status" label="状态" width="100">
                    <template #default="scope">
                        <span :class="['status-tag', getStatusClass(scope.row.status)]">
                            {{ getStatusText(parseInt(scope.row.status)) }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column fixed prop="stockOutDate" label="出库日期" width="120">
                    <template #default="scope">
                        {{ formatDate(scope.row.stockOutDate) }}
                    </template>
                </el-table-column>
                <el-table-column prop="warehouseName" label="仓库名称" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.warehouseName, getSelectedWarehouseName(searchForm.warehouseLocation))"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="sourceOrderNo" label="关联单号" width="150">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.sourceOrderNo, searchForm.stockOutOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="customerName" label="客户名称" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.customerName, searchForm.stockOutOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="contactPerson" label="联系人" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.contactPerson, searchForm.stockOutOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="contactPhone" label="联系方式" width="130">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.contactPhone, searchForm.stockOutOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="goodsName" label="销售货品" width="200">
                    <template #default="scope">
                        <el-tooltip v-if="scope.row.goodsName && scope.row.goodsName.length > 10"
                                    effect="dark"
                                    :content="scope.row.goodsName"
                                    placement="top">
                            <span>{{ truncateText(scope.row.goodsName, 10) }}</span>
                        </el-tooltip>
                        <span v-else>{{ scope.row.goodsName || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="outStockQuantity" label="出库数量" width="120"></el-table-column>
                <el-table-column prop="outStockAmount" label="出库金额" width="120"></el-table-column>
                <el-table-column prop="operatorName" label="经办人" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.operatorName, searchForm.stockOutOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="creatorName" label="制单人" width="100">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.creatorName, searchForm.stockOutOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="departmentName" label="所在部门" width="100">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.departmentName, searchForm.stockOutOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="制单时间" width="160">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="auditorName" label="审核人" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.auditorName, searchForm.stockOutOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="auditorTime" label="审核时间" width="160">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.auditorTime) }}
                    </template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column fixed="right" label="操作" min-width="130">
                    <template #default="scope">
                        <!-- 1. 草稿(0)/待审核(1)状态：显示【编辑】【删除】 -->
                        <el-button v-if="scope.row.status === '0' || scope.row.status === '1'"
                                   class="operate-btn"
                                   link type="primary" size="default"
                                   v-on:click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button v-if="scope.row.status === '0' || scope.row.status === '1'"
                                   class="operate-btn"
                                   link type="danger" size="default"
                                   v-on:click="deleteSingleOutboundOrder(scope.row)">
                            删除
                        </el-button>

                        <!-- 3. 已驳回(2)状态：显示【编辑】【撤销】 -->
                        <el-button v-if="scope.row.status === '2'"
                                   class="operate-btn"
                                   link type="primary" size="default"
                                   v-on:click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button v-if="scope.row.status === '2'"
                                   class="operate-btn"
                                   link type="warning" size="default"
                                   v-on:click="handleRejectCancel(scope.row)">
                            撤销
                        </el-button>

                        <!-- 4. 已审核(3)状态：显示【关闭】 -->
                        <el-button v-if="scope.row.status === '3'"
                                   class="operate-btn"
                                   link type="warning" size="default"
                                   v-on:click="closeOutboundOrder(scope.row)">
                            关闭
                        </el-button>

                        <!-- 5. 已关闭(4)状态：显示【启用】 -->
                        <el-button v-if="scope.row.status === '4'"
                                   class="operate-btn"
                                   link type="success" size="default"
                                   v-on:click="enableOutboundOrder(scope.row)">
                            启用
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage"
                           v-model:page-size="pageSize"
                           :page-sizes="[10, 20, 50, 100]"
                           :total="filteredData.length"
                           layout="total, sizes, prev, pager, next, jumper"
                           v-on:size-change="handleSizeChange"
                           v-on:current-change="handleCurrentChange">
            </el-pagination>
        </div>
    </div>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="出库单审核" width="500px">
        <div style="padding: 20px;">
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: bold;">审核结果</label>
                <el-radio-group v-model="auditResult">
                    <el-radio label="通过" style="margin-right: 20px;">审核通过</el-radio>
                    <el-radio label="驳回">审核驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <label style="display: block; margin-bottom: 8px; font-weight: bold;">审核意见</label>
                <el-input type="textarea"
                          v-model="auditOpinion"
                          rows="4"
                          placeholder="请输入审核意见（可选）"
                          maxlength="200"
                          show-word-limit></el-input>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="auditDialogVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="submitAudit">确定</el-button>
            </div>
        </template>
    </el-dialog>
</div>

<script>
    const { createApp, ref, onMounted, computed } = Vue;
    const { ElMessageBox, ElMessage, ElNotification } = ElementPlus;

    // 状态映射配置
    const STATUS_CONFIG = {
        '0': { text:"初稿", class: 'status-draft' },
        '1': { text:"待审核", class: 'status-pending' },
        '2': { text:"驳回", class: 'status-rejected' },
        '3': { text:"已完成", class: 'status-approved' },
        '4': { text:"已关闭", class: 'status-closed' }
    };

    const app = createApp({
        setup() {
            // -------------------------- 1. 基础数据初始化 --------------------------
            // 原始数据备份
            const originalData = ref([]);

            // 初始化加载数据
            const refreshData = async () => {
                try {
                    const response = await axios.post('/WhOutbound/GetAll');
                    if (response.data.code === 200) {
                        originalData.value = response.data.data;
                        tableData.value = [...originalData.value];
                        ElMessage.success('出库单数据加载成功');
                    }
                } catch (error) {
                    console.error('加载出错:', error);
                    ElMessage.error('数据加载失败，请重试');
                }
            };

            // 加载字典数据
            const loadDictData = async () => {
                try {
                    const response = await axios.post('/WhOutbound/GetDictData');
                    if (response.data.code === 200) {
                        outboundTypes.value = response.data.data.outboundTypes;
                        statusList.value = response.data.data.statusList;
                    }
                } catch (error) {
                    console.error('加载字典数据出错:', error);
                }
            };

            // 搜索表单
            const searchForm = ref({
                stockOutOrderNo: '',
                stockOutType: '',
                status: '',
                warehouseLocation: []
            });

            // 字典数据
            const outboundTypes = ref([]);
            const statusList = ref([]);

            // 仓库库位数据
            const warehouseLocationOptions = ref([]);

            // 表格数据
            const tableData = ref([]);

            // 选中行数据
            const selectedRows = ref([]);
            // 表格实例
            const multipleTable = ref(null);

            // -------------------------- 2. 前端查询逻辑 --------------------------
            // 过滤后的数据
            const filteredData = computed(() => {
                let result = tableData.value;

                // 出库单号模糊查询
                if (searchForm.value.stockOutOrderNo) {
                    const keyword = searchForm.value.stockOutOrderNo.toLowerCase();
                    result = result.filter(item =>
                        (item.stockOutOrderNo && item.stockOutOrderNo.toLowerCase().includes(keyword)) ||
                        (item.sourceOrderNo && item.sourceOrderNo.toLowerCase().includes(keyword)) ||
                        (item.customerName && item.customerName.toLowerCase().includes(keyword)) ||
                        (item.contactPerson && item.contactPerson.toLowerCase().includes(keyword)) ||
                        (item.contactPhone && item.contactPhone.toLowerCase().includes(keyword)) ||
                        (item.goodsName && item.goodsName.toLowerCase().includes(keyword)) ||
                        (item.operatorName && item.operatorName.toLowerCase().includes(keyword)) ||
                        (item.creatorName && item.creatorName.toLowerCase().includes(keyword)) ||
                        (item.departmentName && item.departmentName.toLowerCase().includes(keyword)) ||
                        (item.auditorName && item.auditorName.toLowerCase().includes(keyword))
                    );
                }

                // 出库类型查询 - 根据显示文字匹配
                if (searchForm.value.stockOutType) {
                    const selectedTypeText = getOutboundTypeText(searchForm.value.stockOutType);
                    result = result.filter(item => {
                        const itemTypeText = getOutboundTypeText(item.stockOutType);
                        return itemTypeText === selectedTypeText;
                    });
                }

                // 状态查询 - 根据显示文字匹配
                if (searchForm.value.status) {
                    const selectedStatusText = getStatusText(parseInt(searchForm.value.status));
                    result = result.filter(item => {
                        const itemStatusText = getStatusText(parseInt(item.status));
                        return itemStatusText === selectedStatusText;
                    });
                }

                // 仓库查询 - 根据仓库名称文字匹配
                if (searchForm.value.warehouseLocation && searchForm.value.warehouseLocation.length > 0) {
                    const selectedWarehouseName = getSelectedWarehouseName(searchForm.value.warehouseLocation);
                    if (selectedWarehouseName) {
                        result = result.filter(item =>
                            item.warehouseName && item.warehouseName.includes(selectedWarehouseName)
                        );
                    }
                }

                return result;
            });

            // -------------------------- 3. 分页逻辑 --------------------------
            const currentPage = ref(1);
            const pageSize = ref(10);
            const total = computed(() => filteredData.value.length);
            const paginatedData = computed(() => {
                const start = (currentPage.value - 1) * pageSize.value;
                const end = start + pageSize.value;
                return filteredData.value.slice(start, end);
            });

            const handleSizeChange = (val) => {
                pageSize.value = val;
                currentPage.value = 1;
            };

            const handleCurrentChange = (val) => {
                currentPage.value = val;
                if (multipleTable.value) {
                    multipleTable.value.clearSelection();
                    selectedRows.value = [];
                }
            };

            // -------------------------- 4. 关键字高亮方法 --------------------------
            const highlightText = (text, keyword) => {
                if (!text) return '';
                if (!keyword) return text;

                const str = String(text);
                const key = String(keyword);

                // 创建正则表达式，忽略大小写
                const regex = new RegExp(`(${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
                return str.replace(regex, '<span class="highlight-text">$1</span>');
            };

            // 获取选中仓库的名称
            const getSelectedWarehouseName = (warehousePath) => {
                if (!warehousePath || warehousePath.length === 0) return '';

                let currentNode = warehouseLocationOptions.value;
                let warehouseName = '';

                // 遍历路径找到最后一级节点（仓库名称）
                for (let i = 0; i < warehousePath.length; i++) {
                    const nodeId = warehousePath[i];
                    const foundNode = currentNode.find(node => node.id === nodeId);

                    if (foundNode) {
                        warehouseName = foundNode.name; // 获取节点名称
                        if (foundNode.children && i < warehousePath.length - 1) {
                            currentNode = foundNode.children;
                        }
                    } else {
                        break;
                    }
                }

                return warehouseName;
            };

            // -------------------------- 5. 仓库数据加载 --------------------------
            // 加载仓库和库位数据
            const loadWarehouseLocationData = async () => {
                try {
                    // 获取仓库列表
                    const warehouseRes = await axios.post('/BiProduct/WhAll');
                    if (warehouseRes.data.code === 200) {
                        const warehouses = warehouseRes.data.data;
                        warehouseLocationOptions.value = warehouses.map(wh => ({
                            id: wh.warehouseId,
                            name: wh.warehouseName,
                            children: wh.children || []
                        }));
                    }
                } catch (error) {
                    console.error('加载仓库库位数据失败：', error);
                    ElMessage.error('加载仓库库位数据失败');
                }
            };

            // -------------------------- 6. 状态转换辅助方法 --------------------------
            // 根据状态值获取样式类
            const getStatusClass = (status) => {
                return STATUS_CONFIG[status]?.class || 'status-draft';
            };

            // 根据状态int值获取显示文字
            const getStatusText = (status) => {
                return STATUS_CONFIG[status]?.text || '未知状态';
            };

            // -------------------------- 7. 审核相关逻辑 --------------------------
            const auditDialogVisible = ref(false);
            const auditResult = ref('通过');
            const auditOpinion = ref('');
            const currentAuditRow = ref(null);
            const auditQueue = ref([]);
            const currentAuditIndex = ref(0);

            // 获取当前用户ID
            const getCurrentUserId = () => {
                const userStr = sessionStorage.getItem('YH');
                if (!userStr) {
                    ElMessage.warning('未检测到登录状态，请重新登录');
                    return '';
                }
                try {
                    const userObj = JSON.parse(userStr);
                    const userId = userObj?.id?.toString() || '';
                    if (!userId) {
                        ElMessage.warning('用户信息不完整，请重新登录');
                    }
                    return userId;
                } catch (error) {
                    console.error('解析用户信息失败：', error);
                    ElMessage.error('用户信息异常，请重新登录');
                    return '';
                }
            };

            // 批量审核入口
            const batchAuditOutboundOrder = () => {
                if (selectedRows.value.length === 0) {
                    ElMessage({ type: 'warning', message: '请先选中需要审核的出库单！' });
                    return;
                }

                // 筛选出待审核状态的订单
                const pendingAuditRows = selectedRows.value.filter(row => row.status === '1');
                if (pendingAuditRows.length === 0) {
                    ElMessage({ type: 'error', message: '选中的出库单中没有待审核状态的出库单！' });
                    return;
                }

                // 初始化审核队列
                auditQueue.value = pendingAuditRows;
                currentAuditIndex.value = 0;

                // 开始审核第一个订单
                startNextAudit();
            };

            // 开始下一个订单审核
            const startNextAudit = () => {
                if (currentAuditIndex.value < auditQueue.value.length) {
                    const currentRow = auditQueue.value[currentAuditIndex.value];
                    currentAuditRow.value = currentRow;
                    auditResult.value = '通过'; // 重置为默认值
                    auditOpinion.value = ''; // 清空审核意见
                    auditDialogVisible.value = true;
                } else {
                    // 所有订单审核完成
                    ElMessage.success(`批量审核完成！共审核${auditQueue.value.length}条出库单`);
                    auditQueue.value = [];
                    currentAuditIndex.value = 0;
                    refreshData(); // 刷新数据
                    selectedRows.value = []; // 清空选中状态
                }
            };

            // 提交审核
            const submitAudit = async () => {
                if (!currentAuditRow.value) {
                    ElMessage.warning('请选择要审核的出库单');
                    return;
                }

                const row = currentAuditRow.value;
                const newStatus = auditResult.value === '通过' ? '3' : '2'; // 通过→已完成，驳回→驳回
                const usersId = getCurrentUserId();

                if (!usersId) {
                    ElMessage.error('无法获取用户信息，请重新登录');
                    return;
                }

                try {
                    // 调用审核接口 - 匹配后端Auditor类
                    const response = await axios.post('/WhOutbound/UpdateAuditorComment', {
                        Id: row.stockOutOrderId,
                        OrderStatus: newStatus,
                        AuditorComment: auditOpinion.value,
                        AuditorBy: usersId,
                        AuditorTime: new Date().toISOString()
                    });

                    if (response.data.code === 200) {
                        // 更新前端表格数据
                        const index = tableData.value.findIndex(item => item.stockOutOrderId === row.stockOutOrderId);
                        if (index !== -1) {
                            tableData.value[index].status = newStatus;
                            tableData.value[index].auditorBy = usersId;
                            tableData.value[index].auditorTime = new Date().toISOString();
                            tableData.value[index].auditorComment = auditOpinion.value;
                        }

                        ElMessage.success(`出库单 ${row.stockOutOrderNo} 审核${auditResult.value}`);
                        auditDialogVisible.value = false;

                        // 审核索引+1，继续下一个
                        currentAuditIndex.value++;
                        // 延迟打开下一个审核窗口，提升用户体验
                        setTimeout(() => {
                            startNextAudit();
                        }, 500);
                    } else {
                        ElMessage.error(response.data.msg || '审核失败');
                    }
                } catch (error) {
                    console.error('审核接口请求失败:', error);
                    ElMessage.error('审核失败，请稍后重试');
                }
            };

            // 取消审核
            const cancelAudit = () => {
                auditDialogVisible.value = false;
                // 询问是否继续审核下一个
                ElMessageBox.confirm(
                    '是否要继续审核下一个出库单？',
                    '确认取消',
                    {
                        confirmButtonText: '继续下一个',
                        cancelButtonText: '停止审核',
                        type: 'info'
                    }
                ).then(() => {
                    currentAuditIndex.value++;
                    startNextAudit();
                }).catch(() => {
                    // 取消后续审核
                    ElMessage.info('已停止批量审核');
                    auditQueue.value = [];
                    currentAuditIndex.value = 0;
                });
            };

            // -------------------------- 8. 核心操作方法 --------------------------
            // 8.1 选中行变化
            const handleSelectionChange = (val) => {
                selectedRows.value = val;
            };

            // 8.2 编辑（仅草稿0/待审核1/已驳回2可执行）
            const handleEdit = (row) => {
                const allowEditStatus = ['0', '1', '2'];
                if (!allowEditStatus.includes(row.status)) {
                    ElMessage({
                        type: 'error',
                        message: `当前「${getStatusText(row.status)}」状态不允许编辑！`
                    });
                    return;
                }
                ElNotification({
                    title: '编辑出库单',
                    message: `编辑出库单：${row.stockOutOrderNo}`,
                    type: 'info'
                });
                window.location.href = `/WhOutbound/Edit?id=${row.stockOutOrderId}`;
            };

            // 8.3 单行删除（仅草稿0/待审核1可执行）
            const deleteSingleOutboundOrder = (row) => {
                if (row.status !== '0' && row.status !== '1') {
                    ElMessage({
                        type: 'error',
                        message: `当前「${getStatusText(row.status)}」状态不允许删除！`
                    });
                    return;
                }
                ElMessageBox.confirm(
                    `确定删除出库单 "${row.stockOutOrderNo}" 吗？删除后不可恢复！`,
                    '警告',
                    { type: 'error' }
                ).then(async () => {
                    try {
                        const response = await axios.post(`/WhOutbound/Delete?id=${row.stockOutOrderId}`);
                        if (response.data.code === 200) {
                            tableData.value = tableData.value.filter(item => item.stockOutOrderId !== row.stockOutOrderId);
                            originalData.value = originalData.value.filter(item => item.stockOutOrderId !== row.stockOutOrderId);
                            ElMessage({ type: 'success', message: '删除成功！' });
                        } else {
                            ElMessage({ type: 'error', message: response.data.msg || '删除失败' });
                        }
                    } catch (error) {
                        console.error('删除出错:', error);
                        ElMessage({ type: 'error', message: '删除失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消删除' });
                });
            };

            // 8.4 撤销操作（仅已驳回2可执行）
            const handleRejectCancel = (row) => {
                if (row.status !== '2') {
                    ElMessage({
                        type: 'error',
                        message: `当前「${getStatusText(row.status)}」状态不允许撤销！`
                    });
                    return;
                }
                ElMessageBox.confirm(
                    `确定撤销驳回状态，将出库单"${row.stockOutOrderNo}"恢复为「待审核」吗？`,
                    '确认撤销',
                    { type: 'warning' }
                ).then(async () => {
                    try {
                        // 使用状态变更接口
                        const response = await axios.post(`/WhOutbound/AuditorStatus?status=1&id=${row.stockOutOrderId}`);
                        if (response.data.success) {
                            row.status = '1';
                            row.auditorBy = '';
                            row.auditorTime = '';
                            row.auditorComment = '';
                            ElMessage({ type: 'success', message: '撤销成功！' });
                        } else {
                            ElMessage({ type: 'error', message: response.data.msg || '撤销失败' });
                        }
                    } catch (error) {
                        console.error('撤销出错:', error);
                        ElMessage({ type: 'error', message: '撤销失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消撤销' });
                });
            };

            // 8.5 关闭出库单（仅已完成3可执行）
            const closeOutboundOrder = (row) => {
                ElMessageBox.confirm(
                    `确定关闭出库单"${row.stockOutOrderNo}"吗？`,
                    '确认关闭',
                    { type: 'warning' }
                ).then(async () => {
                    try {
                        // 使用状态变更接口
                        const response = await axios.post(`/WhOutbound/Status?status=4&id=${row.stockOutOrderId}`);
                        if (response.data.success) {
                            row.status = '4';
                            ElMessage({ type: 'success', message: '出库单已关闭！' });
                        } else {
                            ElMessage({ type: 'error', message: response.data.msg || '关闭失败' });
                        }
                    } catch (error) {
                        console.error('关闭出错:', error);
                        ElMessage({ type: 'error', message: '关闭失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消关闭' });
                });
            };

            // 8.6 启用出库单（仅已关闭4可执行）
            const enableOutboundOrder = (row) => {
                ElMessageBox.confirm(
                    `确定启用出库单"${row.stockOutOrderNo}"吗？`,
                    '确认启用',
                    { type: 'info' }
                ).then(async () => {
                    try {
                        // 使用状态变更接口
                        const response = await axios.post(`/WhOutbound/Status?status=3&id=${row.stockOutOrderId}`);
                        if (response.data.success) {
                            row.status = '3';
                            ElMessage({ type: 'success', message: '出库单已启用！' });
                        } else {
                            ElMessage({ type: 'error', message: response.data.msg || '启用失败' });
                        }
                    } catch (error) {
                        console.error('启用出错:', error);
                        ElMessage({ type: 'error', message: '启用失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消启用' });
                });
            };

            // 8.7 批量删除（仅草稿0/待审核1可执行）
            const deleteOutboundOrder = () => {
                if (selectedRows.value.length === 0) {
                    ElMessage({ type: 'warning', message: '请先选中需要删除的出库单！' });
                    return;
                }
                const canDeleteRows = selectedRows.value.filter(row =>
                    row.status === '0' || row.status === '1'
                );
                if (canDeleteRows.length === 0) {
                    ElMessage({ type: 'error', message: '仅「初稿」或「待审核」状态的出库单可删除！' });
                    return;
                }
                const deleteIds = canDeleteRows.map(row => row.stockOutOrderId);
                ElMessageBox.confirm(
                    `确定删除选中的 ${canDeleteRows.length} 条出库单吗？`,
                    '警告',
                    { type: 'error' }
                ).then(async () => {
                    try {
                        for (const id of deleteIds) {
                            await axios.post(`/WhOutbound/Delete?id=${id}`);
                        }
                        tableData.value = tableData.value.filter(row => !deleteIds.includes(row.stockOutOrderId));
                        originalData.value = originalData.value.filter(row => !deleteIds.includes(row.stockOutOrderId));
                        ElMessage({ type: 'success', message: '删除成功！' });
                        selectedRows.value = [];
                    } catch (error) {
                        console.error('批量删除出错:', error);
                        ElMessage({ type: 'error', message: '删除失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消删除' });
                });
            };

            // -------------------------- 9. 查询相关方法 --------------------------
            // 查询方法
            const searchTable = () => {
                currentPage.value = 1;
                ElMessage({
                    type: 'success',
                    message: `查询到 ${filteredData.value.length} 条数据！`
                });
            };

            // 重置表单
            const resetForm = () => {
                searchForm.value = {
                    stockOutOrderNo: '',
                    stockOutType: '',
                    status: '',
                    warehouseLocation: []
                };
                tableData.value = [...originalData.value];
                currentPage.value = 1;
                ElMessage({ type: 'success', message: '查询条件已重置！' });
            };

            // -------------------------- 10. 其他辅助方法 --------------------------
            // 日期格式化
            const formatDateTime = (date) => {
                if (!date) return '';
                const dt = new Date(date);
                const year = dt.getFullYear();
                const month = String(dt.getMonth() + 1).padStart(2, '0');
                const day = String(dt.getDate()).padStart(2, '0');
                const hours = String(dt.getHours()).padStart(2, '0');
                const minutes = String(dt.getMinutes()).padStart(2, '0');
                const seconds = String(dt.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            };

            // 日期格式化（仅日期）
            const formatDate = (date) => {
                if (!date) return '';
                const dt = new Date(date);
                const year = dt.getFullYear();
                const month = String(dt.getMonth() + 1).padStart(2, '0');
                const day = String(dt.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };

            // 出库单号点击跳转页面
            const jumpToDetail = (row) => {
                ElMessage({ type: 'info', message: `跳转至出库单${row.stockOutOrderNo}的详情页` });
                window.location.href = `/WhOutbound/Details?id=${row.stockOutOrderId}&pwd=114514`;
            };

            // 导出
            const exportTable = () => {
                ElMessage({ type: 'success', message: '导出请求已触发，正在下载...' });
            };

            // 刷新
            const refreshTable = () => {
                if (multipleTable.value) {
                    multipleTable.value.clearSelection();
                    selectedRows.value = [];
                }
                currentPage.value = 1;
                refreshData(); // 重新加载数据
                ElMessage({ type: 'success', message: '表格已刷新！' });
            };

            // 新增
            const addOutboundOrder = () => {
                ElNotification({ title: '提示', message: '跳转至新增出库单页面', type: 'info' });
                window.location.href = '/WhOutbound/Create';
            };

            // 复制
            const copyOutboundOrder = () => {
                if (selectedRows.value.length === 0) {
                    ElMessage({ type: 'warning', message: '请先选中需要复制的出库单！' });
                    return;
                }
                if (selectedRows.value.length > 1) {
                    ElMessage({ type: 'warning', message: '仅支持单条出库单复制！' });
                    return;
                }
                const targetRow = selectedRows.value[0];
                ElNotification({ title: '复制出库单', message: `开始复制出库单：${targetRow.stockOutOrderNo}`, type: 'info' });
            };

            // 编辑（批量选择）
            const editOutboundOrder = () => {
                if (selectedRows.value.length === 0) {
                    ElMessage({ type: 'warning', message: '请先选中需要编辑的出库单！' });
                    return;
                }
                if (selectedRows.value.length > 1) {
                    ElMessage({ type: 'warning', message: '仅支持单条出库单编辑！' });
                    return;
                }
                const targetRow = selectedRows.value[0];
                handleEdit(targetRow);
            };

            // 导入
            const importOutboundOrder = () => {
                ElNotification({ title: '导入出库单', message: '打开出库单导入窗口', type: 'info' });
            };

            // 根据出库类型值获取显示文本
            const getOutboundTypeText = (value) => {
                if (!value) return ''; // 空值处理
                // 在outboundTypes中查找匹配的项
                const matched = outboundTypes.value.find(item => item.label === value);
                return matched ? matched.value : `未知类型(${value})`; // 未匹配时显示原始值
            };

            // 页面挂载
            onMounted(() => {
                refreshData();
                loadDictData();
                loadWarehouseLocationData(); // 加载仓库数据
            });
                            // 文本截断方法
    const truncateText = (text, maxLength) => {
        if (!text) return '-';
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    };
            // 暴露数据和方法
            return {
                // 搜索表单
                searchForm,
                outboundTypes,
                statusList,
                warehouseLocationOptions,
                getOutboundTypeText,
                truncateText,
                // 表格相关
                tableData,
                paginatedData,
                filteredData,
                selectedRows,
                multipleTable,
                handleSelectionChange,
                handleEdit,
                deleteSingleOutboundOrder,
                handleRejectCancel,
                closeOutboundOrder,
                enableOutboundOrder,
                getStatusClass,
                getStatusText,

                // 分页相关
                currentPage,
                pageSize,
                total,
                handleSizeChange,
                handleCurrentChange,

                // 审核相关
                auditDialogVisible,
                auditResult,
                auditOpinion,
                batchAuditOutboundOrder,
                submitAudit,
                cancelAudit,

                // 高亮相关
                highlightText,
                getSelectedWarehouseName,

                // 按钮方法
                addOutboundOrder,
                editOutboundOrder,
                deleteOutboundOrder,
                copyOutboundOrder,
                importOutboundOrder,
                exportTable,
                refreshTable,
                resetForm,
                searchTable,
                formatDateTime,
                formatDate,
                jumpToDetail
            };
        }
    });
    app.use(ElementPlus, {
       locale: ElementPlusLocaleZhCn
    });
    app.mount('#app');
</script>
<style>
    /* 样式保持不变 */
    body {
        margin: 0;
        padding: 0;
        font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
        background-color: #f5f7fa;
    }

    #tableBlock {
        margin: 20px auto;
        width: 100%;
        max-width: max-content;
        padding-bottom: 20px;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        background-color: #fff;
        border-radius: 6px;
    }

    .search-area {
        padding: 20px;
        border-bottom: 0px solid #ebeef5;
    }

    .formTableInput, .formTableSelect {
        display: inline-block;
        width: 180px;
    }

    .buttonBlock {
        height: 40px;
        width: 100%;
        padding: 20px;
        gap: 10px;
        margin-bottom: 15px;
        flex-wrap: wrap;
    }

    .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
        padding: 0 20px;
    }

    .audit-textarea {
        margin-top: 15px;
        width: 100%;
    }

    /* 操作列按钮间距 */
    .operate-btn {
        margin-right: 8px;
    }

    .btnAndTable {
        margin: 0 auto;
        padding: 0 20px;
    }

    .search-row {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 15px;
    }

    .search-item {
        display: flex;
        align-items: center;
    }

        .search-item label {
            min-width: 80px;
            text-align: right;
            margin-right: 10px;
        }

    .status-tag {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
    }

    .status-draft {
        background-color: #f0f0f0;
        color: #666;
    }

    .status-pending {
        background-color: #e6f7ff;
        color: #1890ff;
    }

    .status-rejected {
        background-color: #fff2f0;
        color: #ff4d4f;
    }

    .status-approved {
        background-color: #f6ffed;
        color: #52c41a;
    }

    .status-closed {
        background-color: #f5f5f5;
        color: #8c8c8c;
    }

    /* 关键字高亮样式 */
    .highlight-text {
        background-color: #ffeb3b;
        color: #ff0000;
        font-weight: bold;
        padding: 1px 2px;
        border-radius: 2px;
    }
</style>